package com.kly.user.task.v2;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.HttpUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.api.client.util.Joiner;
import com.google.api.client.util.Lists;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.enums.ParameterTypeEnum;
import com.kly.user.chatterService.ChatService;
import com.kly.user.db.dao.*;
import com.kly.user.db.dbo.UserConversationDBO;
import com.kly.user.db.dbo.UserWlmDBO;
import com.kly.user.db.entity.ChatterOptLogEntity;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.db.entity.UserGreetingCommonContentEntity;
import com.kly.user.db.entity.UserGreetingContentEntity;
import com.kly.user.dto.chatter.request.ConversationReq;
import com.kly.user.enums.AppEnum;
import com.kly.user.enums.OnlineStatus;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.task.enums.TaskTypeEnum;
import org.apache.logging.log4j.util.Strings;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ChatterRemindTask {

    private static Log logger = LogFactory.getLog(ChatterRemindTask.class);

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;
    @NacosValue(value = "${enable.chatter.remind.switch:true}", autoRefreshed = true)
    private Boolean enableFlashChatSwitch;
    @NacosValue(value = "${time.between:60}", autoRefreshed = true)
    private long overTimes;
    @Resource
    UserDao userDao;
    @Resource
    ChatterOptLogDao chatterOptLogDao;
    @Resource
    AsyncEventBus pushEventBus;


    private String localIP = NetUtil.getLocalhostStr();


    @Scheduled(fixedDelay = 1000 * 60)
    public void run() {
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============ChatterRemindTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        if (!enableFlashChatSwitch) {
            logger.info("=============ChatterRemindTask, enableFlashchatSwitch:{}", enableFlashChatSwitch);
            return;
        }

        final List<UserEntity> allChatters = userDao.selectAllChatter();
        if (CollectionUtils.isEmpty(allChatters)) {
            return;
        }

        allChatters.forEach(chatter -> {
            final ChatterOptLogEntity chatterLog = chatterOptLogDao.queryLatestRecord(chatter.getUserCode());
            if (chatterLog != null) {
                final long timeBetween = DateUtil.betweenMs(new Date(), chatterLog.getGmtCreate());
                logger.info("chatterUserCode:{}, latestOptLogTime:{}, timeBetween:{}", chatter.getUserCode(), chatter.getGmtCreate(), timeBetween);
                if (timeBetween > overTimes * 1000) {
                    pushOnlineStatus(chatter.getUserCode());

                    // 增加一条提醒日志，用于统计
                    ChatterOptLogEntity entity = new ChatterOptLogEntity();
                    entity.setUrl("remindNotice");
                    entity.setUserCode(chatter.getUserCode());
                    chatterOptLogDao.insert(entity);
                }
            }

        });
    }


    private void pushOnlineStatus(String userCode) {
        Map<String, Object> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.PUSH_REMIND.getId());
        params.put("target", userCode);
        params.put("bizCode", "M20003");
        params.put("token", userCode);
        params.put("userCode", userCode);
        final Event event = Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(userCode).toUserCode(userCode).app(AppEnum.MECHAT).content(JSONObject.toJSONString(params)).build();
        pushEventBus.post(event);
    }

}
